package com.shop.transaction;

import com.shop.exception.DAOException;
import com.shop.exception.NoStartTransaction;
import com.shop.util.ConnectionUtils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @title 事务类
 * @description 对JDBC提供的方法进行封装，实现事务类
 * @author zheng
 * @date 2021-9-28
 * @version 1.0
 */
public class TransactionManager {

    private static Connection conn;

    /**
     * 开启事务
     * @throws DAOException DAO层异常 数据库 网络等问题
     */
    public void openTransaction() throws DAOException {
        try {
            this.conn = ConnectionUtils.getConnection();
            conn.setAutoCommit(false);
        } catch (SQLException throwables) {
            System.out.println(throwables.getMessage());
            throw new DAOException(throwables);
        }
    }

    /**
     * 事务提交
     * @throws DAOException DAO层异常 数据库 网络等问题
     */
    public void commit() throws DAOException {
        try {
            conn.commit();
        } catch (SQLException throwables) {
            System.out.println(throwables.getMessage());
            throw new DAOException(throwables);
        }
    }

    /**
     * 事务回滚
     * @throws DAOException DAO层异常 数据库 网络等问题
     */
    public void rollback() throws DAOException {
        try {
            conn.rollback();
        } catch (SQLException throwables) {
            System.out.println(throwables.getMessage());
            throw new DAOException(throwables);
        }
    }

    /**
     * 关闭数据库连接对象
     */

    public static void close() {

        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     *
     * @return conn 返回当前开启事务的连接对象
     * @throws NoStartTransaction 事务没有开启，无法获得连接对象
     */
    public static Connection getTransactionConn() {
        if(conn == null) {
            try {
                conn = ConnectionUtils.getConnection();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return conn;
    }
}
